﻿/**
 * Created by Administrator on 2017/3/20.
 */
import axios from 'axios';
import Cookies from 'js-cookie';
import { encrypto, entrypParams } from '@/components/cryptoMy';
import { lsRead } from '@/common/js/ls.js';
import { router } from '../router/index.js';

let hostName = window.location.hostname;
console.log('hostName', hostName);

// axios 公共配置
axios.defaults.timeout = 60000;
// if (process.env.NODE_ENV === 'production') {
if (hostName === 'refuel.com' || hostName === '192.168.121.135') {
  // axios.defaults.baseURL = "refuel/api";
  axios.defaults.baseURL = process.env.APP_VUE_E_BASE_URL;
} else {
  axios.defaults.baseURL = 'http://192.168.121.135:8887';
  //axios.defaults.baseURL = "http://localhost:8887";
}
axios.defaults.withCredentials = true;

// http request 拦截器
axios.interceptors.request.use(
  config => {
    config.headers.Authorization = lsRead('token');
    // config.params = Object.assign({}, config.params, {
    //   'lang': Cookies.get('language') || 'zh'
    // })
    if (
      config.url.indexOf('/user/login') > -1 ||
      config.url.indexOf('/user/getLoginUserInfo') > -1
    ) {
      if (config.method === 'post') {
        config.data = encrypto(JSON.stringify(config.data));
      }
      if (config.method === 'get') {
        config.params = entrypParams(config.params);
      }
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

// http response 拦截器
axios.interceptors.response.use(
  response => {
    console.log('netip', response.headers.netip);
    console.log('conent-code', response.headers['content-code']);
    return response;
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          if (router.currentRoute.path != '/login') {
            router.replace({
              path: '/login',
            });
          }
          break;
      }
    } else {
      console.log(error);
      // router.replace({
      //   path: '/'
      // })
    }
    return Promise.reject(error);
  }
);
export default axios;
